const service = require('../../utils/service.js');
const api = require('../../utils/util.js');
Page({
  data: {
    userInfo: {},
    shopInfo: {},
    goodsList: [],
    goods_id: '',
    hasMoreData: true,
    page: 1,
    idx: ''
  },

  onLoad: function (options) {
    let that = this
    let userInfo = wx.getStorageSync('userInfo')
    this.setData({
      userInfo: userInfo,
      idx: options.index
    })
    this.getShopInfo(function () {
      that.init()
    })
  },
  init: function () {
    let that = this;
    let shopData = wx.getStorageSync('shop_data');
    api.ajax(service.url('goodsSearch'), {
      unionid: shopData.shop_unionid,
      token: shopData.token,
      token_key: shopData.token_key,
      shop_code: that.data.shopInfo.shop_code,
      page: that.data.page
    }, function (res) {
      if (res.code == 0) {
        if (res.data.length > 0) {
          for (var i = 0, len = res.data.length; i < len; i++) {
            that.data.goodsList.push(res.data[i])
          }
          that.setData({
            goodsList: that.data.goodsList,
            hasMoreData: true
          })
        } else {
          that.setData({
            goodsList: that.data.goodsList,
            hasMoreData: false
          })
        }
      } else {
        api.toast(res.message)
      }
    })
  },

   // 获取店铺信息
  getShopInfo: function (cb) {
    let that = this
    api.ajax(service.url('getShopDetail'), {
      userid: wx.getStorageSync('out_user_id')
    }, function (res) {
      that.setData({
        shopInfo: res.data
      })
      cb()
    })
  },

  // 获取选择商品的id
  radioChange: function (e) {
    console.log(e)
    let val = e.detail.value
    var arr = val.split(',')
    let goods_id = arr[0]
    let name = arr[1]
    this.setData({
      goods_id: goods_id,
      goods_name: name
    })
  },
  searchScrollLower: function () {
    let page = this.data.page += 1
    if (this.hasMoreData) {
      this.setData({
        page: page
      })
      this.init()
    } else {
      api.toast('没有更多数据了')
    }
  },
  choic: function () {
    let that = this
    let goods_id = this.data.goods_id
    if (goods_id == '' || goods_id == null) {
      api.toast('请选择需要关联的商品')
      return
    }
    let obj = {
      goods_id: goods_id,
      index: that.data.idx,
      name: that.data.goods_name,
      link_type: 1
    }
    var arr = wx.getStorageSync('goodsLink')
    if (arr) {
      let a = true
      for (var i = 0, len = arr.length; i < len; i++) {
        if (obj.index == arr[i].index) {
          a = true
          arr[i] = obj
        } else {
          a = false
        }
      }
      if (!a) {
        arr.push(obj)
      }
      wx.setStorageSync('goodsLink', arr)
    } else {
      let arr = [obj]
      wx.setStorageSync('goodsLink', arr)
    }

    wx.navigateBack()
  }
})